package com.ccyy.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccyy.manage.model.entity.Dept;
import com.ccyy.manage.dao.DeptMapper;
import com.ccyy.manage.service.DeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 是超超越越啊~
 * @since 2021-07-20
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<Dept> selectAllDeptTree(String username) {
        List<Dept> depts = deptMapper.selectAllTree();
//        如果为admin用户则加多一个跟节点
        if ("admin".equals(username)){
            Dept root = new Dept();
            root.setDeptId(0);
            root.setDeptName("系统部门");
            root.setChildren(depts);
            List<Dept> rootList = new ArrayList<>();
            rootList.add(root);
            return rootList;
        }
        return depts;
    }

    /**
     * 删除当前部门及子部门.
     */
    @Override
    public void deleteCascadeByID(Long deptId) {
//        获取当前子部门的id
        QueryWrapper<Dept> queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",deptId);
        List<Dept> depts = deptMapper.selectList(queryWrapper);
        for (Dept dept : depts) {
            deptMapper.deleteById(dept.getDeptId());
        }
//        最后删除部门id
        deptMapper.deleteById(deptId);
    }
}
